package com.baibei.order.list;

import android.content.Context;
import android.os.CountDownTimer;
import android.util.SparseArray;

import com.baibei.basic.BasicPresenterImpl;
import com.baibei.ebec.quotation.AppQuotationFilter;
import com.baibei.ebec.quotation.QuotationManager;
import com.baibei.ebec.quotation.event.IQuotationEvent;
import com.baibei.ebec.sdk.ApiFactory;
import com.baibei.ebec.sdk.IOrderApi;
import com.baibei.ebec.sdk.ITradeApi;
import com.baibei.ebec.sdk.IUserApi;
import com.baibei.model.BalanceInfo;
import com.baibei.model.OrderInfo;
import com.baibei.model.QuotationInfo;
import com.baibei.model.TradeWebSocketInfo;
import com.baibei.model.event.SubscribeOrderEvent;
import com.baibei.model.event.UnsubscribeOrderEvent;
import com.baibei.quotation.QuotationFilter;
import com.baibei.sdk.ApiDefaultObserver;
import com.baibei.sdk.Empty;
import com.blankj.utilcode.utils.LogUtils;
import com.rae.swift.Rx;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

/**
 * 首页订单列表
 * 展示层
 * Created by shenminjie on 2017/8/10.
 * mail:shenminjie@100bei.com
 */

public class IndexOrderPresenterImpl extends BasicPresenterImpl<IndexOrderContract.IndexOrderView> implements IndexOrderContract.Presenter, IQuotationEvent {

    /**
     * 订单接口
     */
    private IOrderApi mApi;
    private ITradeApi mTradeApi;
    private IUserApi mUserApi;

    /**
     * 订单列表
     */
    private List<OrderInfo> mOrderInfos;

    /**
     * 余额对象
     */
    private BalanceInfo mBalanceInfo;

    /**
     * 用于调用退订接口后，等待平仓推送过程的一个倒计时
     * 倒计时超时
     */
    private CountDownTimer mCountDownTimer = new CountDownTimer(5000, 1000) {
        @Override
        public void onTick(long l) {
        }

        @Override
        public void onFinish() {
            mView.onUnsubscribeTimeout();
        }
    };

    public IndexOrderPresenterImpl(Context context, IndexOrderContract.IndexOrderView view) {
        super(context, view);
        mApi = ApiFactory.getInstance().getOrderApi();
        mUserApi = ApiFactory.getInstance().getUserApi();
        mTradeApi = ApiFactory.getInstance().getTradeApi();
        mOrderInfos = new ArrayList<>();
    }

    @Override
    public void registerQuotation() {
        QuotationFilter filter = new QuotationFilter(AppQuotationFilter.ACTION_TRADE_CLOSED);
        filter.addAction(AppQuotationFilter.ACTION_TRADE_CREATED);
        filter.addAction(QuotationFilter.ACTION_QUOTATION_PRODUCT);
        QuotationManager.getInstance().register(this, filter);
    }

    @Override
    public void unregisterQuotation() {
        QuotationManager.getInstance().unregister(this);
    }

    /**
     * 退订通知
     *
     * @param event event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(UnsubscribeOrderEvent event) {
        int position = -1;
        for (int i = 0; i < mOrderInfos.size(); i++) {
            OrderInfo info = mOrderInfos.get(i);
            if (info.getOrderid().equals(event.orderId)) {
                position = i;
                break;
            }
        }
        if (position != -1) {
            mOrderInfos.remove(position);
            mView.onLoadOrderList(mOrderInfos);
            mView.updateMyIncome(mOrderInfos);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(SubscribeOrderEvent event) {
        start();
    }

    @Override
    public void start() {
        //订单列表
        createObservable(mApi.getOrderList()).subscribe(new ApiDefaultObserver<List<OrderInfo>>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                    mView.onRefreshCompeted();
                    mView.onLoadFailed(s);
                }
            }

            @Override
            protected void accept(List<OrderInfo> infos) {
                mOrderInfos = infos;
                if (mView != null) {
                    mView.onRefreshCompeted();
                    mView.onLoadOrderList(mOrderInfos);
                    mView.updateMyIncome(mOrderInfos);
                }
            }
        });
        //余额
        createObservable(mUserApi.getBalanceInfo()).subscribe(new ApiDefaultObserver<BalanceInfo>() {
            @Override
            protected void onError(String s) {
                if (mView != null) {
                    mView.onLoadBalanceFailed(s);
                }
            }

            @Override
            protected void accept(BalanceInfo balanceInfo) {
                if (balanceInfo != null && mView != null) {
                    mBalanceInfo = balanceInfo;
                    mView.onLoadBalanceInfo(balanceInfo);
                }
            }
        });
    }


    @Override
    public void destroy() {
        //清空倒计时
        if (mCountDownTimer != null) {
            mCountDownTimer.cancel();
            mCountDownTimer = null;
        }
        super.destroy();
    }

    @Subscribe
    @Override
    public void onEvent(SparseArray<QuotationInfo> quotations) {
        if (Rx.isEmpty(mOrderInfos) || mView == null) return;
        int updateCount = 0;
        for (OrderInfo info : mOrderInfos) {
            //根据现有的订单查找推送行情的改变，如果找到则设置最新价格
            QuotationInfo quotationInfo = quotations.get(Rx.parseInt(info.getProductid()));
            if (quotationInfo == null) continue;
            //如果价格相同，跳过
            if (quotationInfo.getMarketPrice() == info.getLast()) {
                continue;
            }
//            LogUtils.e(info.getName() + "----原价格：" + info.getLast() + "  更新价格:" + quotationInfo.getMarketPrice());
            //记录更新数据，如果集合中有需要更新的，刷新界面
            updateCount++;
            info.setLast(quotationInfo.getMarketPrice());
        }
        if (updateCount != 0) {
            mView.onLoadOrderList(mOrderInfos);
            mView.updateMyIncome(mOrderInfos);
        }
    }


    @Override
    public void unsubscribeOrder(final String orderId, String area) {
        mView.showLoading();
        createObservable(mTradeApi.cancel(orderId, area)).subscribe(new ApiDefaultObserver<Empty>() {
            @Override
            protected void onError(String s) {
                mView.onLoadFailed(s);
                mView.hideLoading();
            }

            @Override
            protected void accept(Empty empty) {
                //退订成功
                //重新刷新界面
                mCountDownTimer.cancel();
                mCountDownTimer.start();
            }
        });
    }


    @Subscribe
    public void onEvent(TradeWebSocketInfo tradeInfo) {
        mCountDownTimer.cancel();
        LogUtils.e("订购websocket推送：" + tradeInfo);
        if ("CODE_CLOSE_SUCCESS".equalsIgnoreCase(tradeInfo.getCode())) {
            mView.hideLoading();
            mView.onUnsubscribeSuccess("退订成功");
        }
        //重新刷新数据
        start();
    }
}
